﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Web;
using System.Web.Mvc;

namespace CodeFarmer.Controller
{
    /// <summary>
    /// 验证码控制器
    /// </summary>
    public class AuthenCodeController : BaseController
    {
        protected HttpContextBase Context = null;
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Context = filterContext.HttpContext;
            base.OnActionExecuting(filterContext);
        }

        public AuthenCode Generate()
        {
            string randomText = GenerateText(4);
            HttpContext.Session["AuthenCode"] = randomText;
            return new AuthenCode()
            {
                BackGroundColor = Color.White,
                RandomTextColor = Color.Maroon,
                RandomText = randomText
            };
        }

        /// <summary>
        /// 生成随机文本。
        /// </summary>
        /// <param name="count">文本长度</param>
        private string GenerateText(int count)
        {
            if (count > 36)
                throw new InvalidOperationException("验证码长度不能超过36。");
            char[] columns = new char[36];
            for (int charPos = 65; charPos < 65 + 26; charPos++)
                columns[charPos - 65] = (char)charPos;
            for (int intPos = 48; intPos <= 57; intPos++)
                columns[26 + (intPos - 48)] = (char)intPos;
            StringBuilder randomBuilder = new StringBuilder();
            Random randomSeed = new Random();
            for (int incr = 0; incr < count; incr++)
                randomBuilder.Append(columns[randomSeed.Next(36)].ToString());
            return randomBuilder.ToString();
        }
    }
}
